package com.rehome.udp;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPSend {
    private DatagramSocket datagramSocket;
    private UDPFrame udpFrame;
    private String sender;

    public UDPSend(DatagramSocket datagramSocket, UDPFrame udpFrame, String sender) {
        this.datagramSocket = datagramSocket;
        this.udpFrame = udpFrame;
        this.sender = sender;
    }

    public void sendMessages() {
        //String send = UDPServerFrame.getSendField().getText();
        //发送消息
        try {
            System.out.println("请输入" + sender + "要发送的消息:");
            String data = udpFrame.getSendField().getText();
            String ip = udpFrame.getIpField().getText();
            int dPacketPort = Integer.parseInt(udpFrame.getDPacketField().getText());
            byte[] bytes = data.getBytes();
            InetAddress inetAddress = InetAddress.getByName(ip);
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, inetAddress, dPacketPort);
            datagramSocket.send(datagramPacket);
            //udpFrame.getTextArea().append("\t" + sender + "发送消息成功\n");
            udpFrame.getTextArea().append("\t\t\t[" + sender + "] : " + data + "\n");

            String ipAddress = datagramPacket.getAddress().getHostAddress();
            System.out.println("ipAddress: " + ipAddress);
            System.out.println("ipField().getText(): " + ip);
        } catch (Exception ex) {
            ex.printStackTrace();
            udpFrame.getTextArea().append("\t" + sender + "尚未连接成功，消息发送失败\n");
        } finally {
            //System.out.println("\t"+sender+"发送消息成功\n");
        }
    }

}
